package com.xmmj.baselibrary.utils.viewadapter.viewpager2

import androidx.databinding.BindingAdapter
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.OnPageChangeCallback
import androidx.fragment.app.FragmentActivity
import android.content.ContextWrapper
import androidx.fragment.app.Fragment
import com.xmmj.baselibrary.utils.adapter.viewpager.ViewPagerAdapter2

@BindingAdapter(value = ["fragments", "onPageChangeCallback"], requireAll = false)
fun setParams(
    viewPager: ViewPager2,
    fragments: List<Fragment>,
    onPageChangeCallback: OnPageChangeCallback,
) {
    if (fragments.isNotEmpty()) {
        viewPager.offscreenPageLimit = fragments.size
        if (viewPager.context is FragmentActivity) {
            viewPager.adapter =
                ViewPagerAdapter2((viewPager.context as FragmentActivity), fragments)
        } else if (viewPager.context is ContextWrapper) {
            viewPager.adapter = ViewPagerAdapter2(
                ((viewPager.context as ContextWrapper).baseContext as FragmentActivity),
                fragments
            )
        }
        onPageChangeCallback.let {
            viewPager.registerOnPageChangeCallback(it)
        }
    }
}

@BindingAdapter(value = ["position"], requireAll = false)
fun setCurrentItem(viewPager: ViewPager2, position: Int) {
    viewPager.setCurrentItem(position, false)
}

@BindingAdapter(value = ["isUserInputEnabled"], requireAll = false)
fun setUserInputEnabled(viewPager: ViewPager2, isUserInputEnabled: Boolean) {
    viewPager.isUserInputEnabled = isUserInputEnabled
}
